package com.shuzijun.blog;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuzijun.blog.pojo.JacksonPerson;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class TestJackson {

    @Test
    public void transformToObject() throws IOException {
        String s = "{\"age\":18,\"cards\":[{\"cardName\":\"招商\",\"cardTime\":\"2021-09-09 20:12:26\"},{\"cardName\":\"浦发\",\"cardTime\":\"2021-09-09 20:12:26\"}],\"name\":\"兵长\"}";
        String list = "[{\"age\":18,\"cards\":[{\"cardName\":\"招商\",\"cardTime\":\"2021-09-09 20:12:26\"},{\"cardName\":\"浦发\",\"cardTime\":\"2021-09-09 20:12:26\"}],\"name\":\"兵长\"},{\"age\":18,\"cards\":[{\"cardName\":\"招商\",\"cardTime\":\"2021-09-09 20:12:26\"},{\"cardName\":\"浦发\",\"cardTime\":\"2021-09-09 20:12:26\"}],\"name\":\"兵长\"}]";
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.readValue(s, JacksonPerson.class));
        List<JacksonPerson> personList = (List<JacksonPerson>)objectMapper.readValue(list, objectMapper.getTypeFactory().constructParametricType(List.class, JacksonPerson.class));
        System.out.println(personList);
        // 如果多层套娃，你可以使TypeReference，万能想要的都有
        List<Map<String,Object>> personList1 = objectMapper.readValue(list, new TypeReference<List<Map<String,Object>>>(){});
        System.out.println(personList1);
    }

}
